﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace BlackJack
{
    public class DealingShoe
    {
        #region private variables
        private Card[] m_cards;
        private const int CARDSPERDECK = 52;
        private int m_noOfDecks;
        private int m_shoePosition;
        private BitmapImage m_shoeTopImage;
        #endregion

        #region Events
        public delegate void ShoeEventHandler(Object obj, EventArgs e);
        public event ShoeEventHandler EndOfShoeEvent;
        public event ShoeEventHandler ShuffleEvent;
        #endregion

        #region Properties
        
        public bool Eod
        {
            get { return (m_shoePosition >= m_cards.Length * 0.75); }
        }

        #endregion

        #region Methods
        public DealingShoe(int noOfDecks)
        {
            m_noOfDecks = noOfDecks;
            m_cards = new Card[m_noOfDecks * CARDSPERDECK];
            m_shoeTopImage = new BitmapImage(new Uri("Images/53.jpg", UriKind.Relative));
            InitShoe();
        }

        private void InitShoe()
        {
            for (int i = 1; i <= m_noOfDecks; i++)
            {
                for(int suit = 0; suit <4; suit++)
                {
                    for (int cardtype = 1; cardtype<= 13; cardtype++)
                    {
                        m_cards[i * cardtype * suit] = new Card((Card.CardType)(cardtype ), (Card.CardSuit)(suit));
                    }
                }
            }
            m_shoePosition = 0;
        }

        //Knuth shuffle algorithm
        public void Shuffle()
        {
            Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
            int r;
            Card temp;
            m_shoePosition = 0;
            for (int j = m_cards.Length; j > 1; j--)
            {
                r = rand.Next(0, j);
                temp = m_cards[j];
                m_cards[j] = m_cards[r];
                m_cards[r] = temp;
            }
            ShuffleEvent(this, EventArgs.Empty);
        }

        public Card NextCard()
        {
            m_shoePosition++;
            if (m_shoePosition <= m_cards.Length - 1)
            {
                if (Eod)
                {
                    EndOfShoeEvent(this, EventArgs.Empty);
                }
            }
            else
            {
                Shuffle();
            }
            return m_cards[m_shoePosition];
        }
        #endregion
    }
}
